import { sleep } from "@/utils";
import IpcParams from "../IpcParams";
import { createAgent } from './utils';
import Axios from 'axios';
import axiosRetry from 'axios-retry';
import { uid } from "uid";


export default class TabizooGame {
  constructor(tokenInfo) {
    this.tokenInfo = tokenInfo
    const agent = createAgent(this.tokenInfo.proxy)
    const headers = {
      "Referer": "https://miniapp.tabibot.com/",
      "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
    }
    this.axios = Axios.create({
      headers: headers,
      httpAgent: agent,
      httpsAgent: agent,
    })
    axiosRetry(this.axios, {
      retries: 10, retryDelay: (retryCount) => {
        return 2000
      }
    });
  }

  async run() {
    try {
      let webSessionUrl = this.tokenInfo.tgweb
      if (webSessionUrl.startsWith("https://") == false) {
        console.error(`${this.gameInfo.phone}  error session url ${webSessionUrl}`);
        return
      }
      webSessionUrl = decodeURIComponent(webSessionUrl)
      let session = webSessionUrl.split("#tgWebAppData=")[1]
      session = session.split("&tgWebAppVersion")[0]
      const headers = {
        rawdata: session,
        "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
      }
      this.headers = headers;
      const inviteUrl = this.tokenInfo.inviteUrl
      let refId = 0
      if (inviteUrl != null) {
        refId = inviteUrl.split("startapp=")[1]
        refId = parseInt(refId)
      }
      // console.log("邀请码", refId)
      const signRes = await this.axios.request("https://api.tabibot.com/api/user/v1/sign-in", {
        method: "post",
        headers: headers,
        data: {
          "referral": refId,
        }
      })
      this.user = signRes.data.data.user
      let profileRes = await this.axios.request("https://api.tabibot.com/api/user/v1/profile", {
        method: "get",
        headers: headers,
      })
      this.user = profileRes.data.data.user
      // 验证是否加入频道和twitter
      const bootRes = await this.axios.request("https://api.tabibot.com/api/task/v1/boot", {
        method: "get",
        headers: headers,
      })
      const bootList = bootRes.data.data
      for (let index = 0; index < bootList.length; index++) {
        const boot = bootList[index];
        if (boot.user_task_status == 2) {
          // verify
          const verifyRes = await this.axios.request("https://api.tabibot.com/api/task/v1/verify/task", {
            method: "post",
            headers: headers,
            data: {
              task_tag: boot.task_tag,
            }
          })
          console.log(boot.task_tag, verifyRes.data.data)
          await sleep(3 * 1000)
        }
      }

      // 收矿+挖矿
      await this.axios.request("https://api.tabibot.com/api/mining/v1/claim", {
        method: "post",
        headers: headers,
      })

      // 游戏逻辑
      await sleep(3 * 1000)
      await this.axios.request("https://api.tabibot.com/api/task/v1/onboarding", {
        method: "post",
        headers,
      })

      await sleep(3 * 1000)
      // 收矿&挖矿
      const infoRes = await this.axios.request("https://api.tabibot.com/api/mining/v1/info", {
        method: "get",
        headers,
      })

      await sleep(3 * 1000)
      const taskListRes = await this.axios.request("https://api.tabibot.com/api/task/v1/list", {
        method: "get",
        headers,
      })
      const taskList = taskListRes.data.data
      for (let index = 0; index < taskList.length; index++) {
        const task = taskList[index];
        // 日常任务
        if (task.project_tag == "task_daily_reward") {
          const subList = task.task_list
          for (let index = 0; index < subList.length; index++) {
            const subtask = subList[index];
            const adsid = uid(5)
            // 看广告
            await this.axios.request("https://api.tabibot.com/api/ads/v1/report", {
              method: "post",
              headers,
              data: {
                status: 3,
                ad_id: adsid,
                from: "task",
              }
            })
            await sleep(16 * 1000)
            await this.axios.request("https://api.tabibot.com/api/ads/v1/report", {
              method: "post",
              headers,
              data: {
                status: 1,
                ad_id: adsid,
                from: "task",
              }
            })
            await sleep(3 * 1000)
            // 完成任务
            const verifyRes = await this.axios.request("https://api.tabibot.com/api/task/v1/verify/task", {
              method: "post",
              headers,
              data: {
                task_tag: subtask.task_tag,
                ad_id: adsid,
              }
            })
            console.log("verify task", verifyRes.data.data)
            await sleep(3 * 1000)
          }
        }
      }

      await sleep(3 * 1000)

      const spinInfoRes = await this.axios.request("https://api.tabibot.com/api/spin/v1/info", {
        method: "post",
        headers,
      })
      await sleep(3 * 1000)
      let energy = spinInfoRes.data.data.energy
      let energyCount = energy.energy
      while (energyCount > 0) {
        const playRes = await this.axios.request("https://api.tabibot.com/api/spin/v1/play", {
          method: "post",
          headers,
          data: {
            multiplier: 1
          }
        })
        if (playRes.data.data != null) {
          energy = playRes.data.data.energy
          energyCount = energy.energy
          console.log("play spin", playRes.data.data.prize.amount)
        }

        await sleep(Math.random() * 1000 + 2000)
      }
      await sleep(1000)
      await this.levelUp()
      await sleep(3 * 1000)
      profileRes = await this.axios.request("https://api.tabibot.com/api/user/v1/profile", {
        method: "get",
        headers: headers,
      })
      this.user = profileRes.data.data.user

      this.tokenInfo.score = this.user.coins
      const date = (new Date()).toLocaleString()
      this.tokenInfo.gameupdate = date
      this.tokenInfo.count = (this.tokenInfo.count || 0) + 1
      console.log(date, "tabizoo end", this.tokenInfo.phone, "score: ", this.tokenInfo.score)
      return new IpcParams("runTabizoo", this.tokenInfo)
    } catch (error) {
      console.log((new Date()).toLocaleString(), "tabizoo error", this.tokenInfo.phone)
      console.error(error)
      return new IpcParams("runTabizoo", this.tokenInfo, error)
    }
  }

  async levelUp() {
    try {
      const res = await this.axios.request("https://api.tabibot.com/api/user/v1/level-up", {
        method: "post",
        headers: this.headers,
      })
      console.log("levelUp", res.data.data)
    } catch (error) {
      console.error("levelUp", error)
    }
  }
}
